<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Pumpio Settings Controller
 *
 * PHP version 5
 * LICENSE: This source file is subject to AGPL license 
 * that is available through the world-wide-web at the following URI:
 * http://www.gnu.org/licenses/agpl.html
 * @author	   Omar Vega Ramos <ovruni@gnu.org.pe> 
 * @copyright      (c) 2012 - 2016 Omar Vega Ramos
 * @license	   http://www.gnu.org/licenses/agpl.html GNU Affero General Public License (AGPL) 
 */

class Pumpio_Settings_Controller extends Admin_Controller {
  
  public function index()
  {
    $this->template->this_page = 'addons';
    
    // Standard Settings View
    $this->template->content = new View("admin/addons/plugin_settings");
    $this->template->content->title = "Pumpio Settings";
    
    // Settings Form View
    $this->template->content->settings_form = new View("pumpio/admin/pumpio_settings");
    
    // setup and initialize form field names
    $form = array(
		  'pumpio_host' => '',
		  'pumpio_username' => '',
		  );
    
    //  Copy the form as errors, so the errors will be stored with keys
    //  corresponding to the form field names
    $errors = $form;
    $form_error = FALSE;
    $form_saved = FALSE;
    $pumpio_connect = '';
    $pumpio_reset = '';
    
    // check, has the form been submitted, if so, setup validation
    if ($_POST) {
      // Instantiate Validation, use $post, so we don't overwrite $_POST
      // fields with our own things
      $post = new Validation($_POST);
      
      // Add some filters
      $post->pre_filter('trim', TRUE);
      
      // Add some rules, the input field, followed by a list of checks, carried out in order
      $post->add_rules('pumpio_host','required', 'length[4,30]');
      $post->add_rules('pumpio_username', 'required', 'length[1,64]');
      $post->add_callbacks('pumpio_host', array($this, 'filter_host'));
      $post->add_callbacks('pumpio_username', array($this, 'filter_username'));
      
      // Test to see if things passed the rule checks
      if ($post->validate()) {
	// Yes! everything is valid
	$pumpio = ORM::factory('pumpio', 1);
	$pumpio->pumpio_host = $post->pumpio_host;
	$pumpio->pumpio_username = $post->pumpio_username;
	$pumpio->save();
	
	// Everything is A-Okay!
	$form_saved = TRUE;
	
	// repopulate the form fields
	$form = arr::overwrite($form, $post->as_array());
	
      // No! We have validation errors, we need to show the form again,
      // with the errors
      } else {
	// repopulate the form fields
	$form = arr::overwrite($form, $post->as_array());
	
	// populate the error fields, if any
	$errors = arr::overwrite($errors, $post->errors('settings'));
	$form_error = TRUE;
      }
    } else {
      // Retrieve Current Settings
      $pumpio = ORM::factory('pumpio', 1);
      
      $form = array(
		    'pumpio_host' => $pumpio->pumpio_host,
		    'pumpio_username' => $pumpio->pumpio_username,
		    );
    }
    /*
    if ($form_error == FALSE) {
      if (($form['pumpio_host'] != '') AND ($form['pumpio_username'] != '')) {
	// Retrieve Current Settings
	$pumpio = ORM::factory('pumpio', 1);
	
	if (($pumpio->oauth_token == '') OR ($pumpio->oauth_token_secret == '')) {
	  $pumpio_connect = url::site('pumpio');
	} else {
	  $pumpio_reset = url::site('admin/pumpio_settings/reset');
	}
      }
    }
    */
    // Pass the $form on to the settings_form variable in the view
    $this->template->content->settings_form->form = $form;
    /*
    $this->template->content->settings_form->pumpio_connect = $pumpio_connect;
    $this->template->content->settings_form->pumpio_reset = $pumpio_reset;
    */
    // Other variables
    $this->template->content->errors = $errors;
    $this->template->content->form_error = $form_error;
    $this->template->content->form_saved = $form_saved;
  }
  
  /**
   * Filtering the hostname if someone is entering it with "http"
   * @param Validation $post $_POST variable with validation rules 
   */
  public function filter_host(Validation $post)
  {
    // If add->rules validation found any errors, get me out of here!
    if (array_key_exists('pumpio_host', $post->errors()))
      return;
    
    $post->pumpio_host = str_replace(array('https://', 'http://', 'www.'), array('', '', ''), $post->pumpio_host);
  }
  
  /**
   * Filtering the username if it is filled wrong
   * @param Validation $post $_POST variable with validation rules 
   */
  public function filter_username(Validation $post)
  {
    // If add->rules validation found any errors, get me out of here!
    if (array_key_exists('pumpio_username', $post->errors()))
      return;
    
    if (strstr($post->pumpio_username, '@')) {
      $pos = strpos($post->pumpio_username, '@');
      if ($pos > 0) {
	$post->pumpio_username = substr($post->pumpio_username, 0, $pos);
      } else {
	$post->pumpio_username = '';
      }
    }
    
    if (!preg_match('/^[a-zA-Z\d_\-.]{1,64}$/', $post->pumpio_username)) {
      $post->add_error('pumpio_username', 'check');
    }
  }
  
  /**
   * Reset Pump.io Settings
   */
  public function reset()
  {
    $this->template = '';
    $this->auto_render = FALSE;
	
    // Retrieve Current Settings
    $pumpio = ORM::factory('pumpio', 1);
    $pumpio->consumer_key = NULL;
    $pumpio->consumer_secret = NULL;
    $pumpio->oauth_token = NULL;
    $pumpio->oauth_token_secret = NULL;
    $pumpio->pumpio_host = '';
    $pumpio->pumpio_username = '';
    $pumpio->save();
    url::redirect('admin/pumpio_settings');
  }
}